#pragma once
#include<iostream>
#include<string>
#include<cstring>
#include<cstdlib>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>


using namespace std;

namespace wyl
{
    class Sock
    {
    public:
        static int Socket()
        {
            int sock = socket(AF_INET,SOCK_STREAM,0);
            if(sock < 0)
            {
                cout<<"Socket failed"<<endl;
                exit(1);
            }
            return sock;
        }

        static void Bind(int sock,uint16_t post)
        {
            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(post);
            local.sin_addr.s_addr = INADDR_ANY;
            if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0)
            {
                cout<<"Bind failed"<<endl;
                exit(2);
            }
        }

        static void Listen(int sock)
        {
            if(listen(sock,5) < 0)
            {
                cout<<"Listen failed"<<endl;
                exit(3);
            }
        }

        static int Accept(int sock)
        {
            struct sockaddr_in client; 
            socklen_t len;
            int fd = accept(sock,(struct sockaddr*)&client,&len); //输出型参数,返回套接字
            if(fd < 0)
                return -1;
            return fd;
        }

        static void Connect(int sock,uint16_t port,string ip)
        {
            struct sockaddr_in server; 
            server.sin_family = AF_INET;
            server.sin_port = htons(port);
            server.sin_addr.s_addr = inet_addr(ip.c_str());
            if(connect(sock,(struct sockaddr*)&server,sizeof(server)) == 0)
                    cout<<"Connect Succeed"<<endl;           
            else
            {
                 cout<<"Connect failed"<<endl;
                    exit(4);
            }

        }
    };
}

